//
//  DPSendCodeButton.m
//  demo
//
//  Created by Andrew on 2017/8/15.
//  Copyright © 2017年 Andrew. All rights reserved.
//

#import "TL_SendCodeButton.h"
#import "TL_GCDTimer.h"

/** 倒计时时长 */
static NSInteger const countdown_time = 60;

@interface TL_SendCodeButton ()

@property (nonatomic, strong) TL_GCDTimer *countdownTimer;

@property (nonatomic, copy) NSString *identifyString;

@property (nonatomic, assign) NSUInteger originalTime;

@end

@implementation TL_SendCodeButton

- (instancetype)initWithFrame:(CGRect)frame identify:(NSString *)identifyString
{
    if (self = [super initWithFrame:frame]) {
        [self.titleLabel setFont:SYSTEM_FONT(14)];
        [self setTitle:WXLocalizedString(@"获取验证码") forState:UIControlStateNormal];
        
        _identifyString = identifyString;
        
        NSInteger saveTime = [self getSaveTime];
        NSInteger old_timestamp = [[NSUserDefaults.standardUserDefaults objectForKey: @"TL_CountdownTimer_EmailStop"] integerValue];
        NSInteger timestamp = [[TL_UtilsHelper getTimeStamp] integerValue];
        NSInteger timeDiff = timestamp - old_timestamp;
        saveTime -= timeDiff;
        
        if (saveTime > 1) {
            self.originalTime = saveTime;
            [self startTiming];
        } else {
            self.originalTime = countdown_time;
        }
        
        MK_WEAK_SELF
        self.countdownTimer.timerFinishedBlock = ^{
            weakSelf.originalTime = countdown_time;
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.enabled = YES;
                [weakSelf setTitle:WXLocalizedString(@"重新发送") forState:UIControlStateNormal];
                [weakSelf mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.width.mas_equalTo(weakSelf.intrinsicContentSize.width + kMargin);
                }];
            });
        };
        
        self.countdownTimer.timerRunningBlock = ^(NSUInteger runTimes, CGFloat currentTime) {
            [weakSelf saveTime:currentTime];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf setTitle:[NSString stringWithFormat:@"(%@)%@", [TL_UtilsHelper formatStringWithInteger:currentTime], WXLocalizedString(@"秒后可重新发送")] forState:UIControlStateNormal];
                [weakSelf mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.width.mas_equalTo(160.0);
                }];
            });
        };
    }
    return self;
}

- (void)startTiming
{
    self.enabled = NO;
    
    [self.countdownTimer startTimerWithTimeDuration:self.originalTime];

    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(160);
    }];
}

#pragma mark -  private

- (NSUInteger)getSaveTime
{
    return [self getSaveTimeWithIdentifySting:_identifyString];
}

- (NSUInteger)getSaveTimeWithIdentifySting:(NSString *)identifyString
{
    
    if (!identifyString) {
        return [[[NSUserDefaults standardUserDefaults] objectForKey:@"VerCodeButtonTime"] integerValue];
    }
    return [[[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"VerCodeButtonTime-%@",identifyString]] integerValue];
}

- (void)saveTime:(NSUInteger)ktime
{
    if (!_identifyString || _identifyString == nil) {
        [[NSUserDefaults standardUserDefaults] setObject:[TL_UtilsHelper formatStringWithInteger:ktime] forKey:@"VerCodeButtonTime"];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:[TL_UtilsHelper formatStringWithInteger:ktime] forKey:[NSString stringWithFormat:@"VerCodeButtonTime-%@",_identifyString]];
    }
}

- (TL_GCDTimer *)countdownTimer
{
    if (!_countdownTimer) {
        _countdownTimer = [[TL_GCDTimer alloc] initCountdownTimerWithTimeDuration:10 immediatelyCallBack:YES];
    }
    return _countdownTimer;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.countdownTimer stopTimer];
    self.countdownTimer = nil;
    [NSUserDefaults.standardUserDefaults setObject:[TL_UtilsHelper getTimeStamp] forKey:(@"TL_CountdownTimer_EmailStop")];
}

@end

